package business;

import models.${model.tableName};
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.transform.Transformers;
import org.hibernate.SQLQuery;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import constants.Templets;
import constants.Constants;
import constants.SupervisorEvent;
import play.Logger;
import play.db.helper.JpaHelper;
import play.db.jpa.JPA;
import utils.ErrorInfo;
import utils.NumberUtil;
import utils.PageBean;
import utils.Security;
import constants.SQLTempletes;
import utils.QueryUtil;
import utils.RegexUtils;
import utils.DateUtil;
/**
 * ${model.comment} 服务层
 * 
 * @author ${model.author}
 * @date ${date}
 */
public class ${model.model} implements Serializable{
	
	public long id;
	private long _id;
	public String sign;//加密ID
#foreach ($field in $fieldList)
#if(${field.field}!="id")
	// ${field.comment}
	public ${field.type} ${field.field};
#end
#end

	public void setId(long id) {
		${model.tableName} ${model.modelL}Entity = null;

		try {
			${model.modelL}Entity = ${model.tableName}.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.info("setId时,根据ID查询${model.comment}：" + e.getMessage());
			this._id = -1;
			
			return;
		}

		if (${model.modelL}Entity == null) {
			this._id = -1;
			
			return;
		}

		this._id = id;
#foreach ($field in $fieldList)
#if(${field.field}!="id")
	this.${field.field} = ${model.modelL}Entity.${field.columnName};// ${field.comment}
#end
#end
	}
	
	public long getId() {
		return _id;
	}
	public String getSign() {
		return Security.addSign(this._id, Constants.SUPERVISOR_ID_SIGN);
	}
	/**
	 * 查询所有${model.comment}
	 * @return
	 */
	public static PageBean<${model.tableName}> query${model.model}All(Map conditionMap,ErrorInfo error) {
		error.clear();

		StringBuffer conditions = new StringBuffer(" delete_status=0 ");
		List<Object> values = new ArrayList<Object>();
		 

#foreach( $field in $fieldList )
#if(${field.matchType}=="any"||${field.matchType}=="eq"||${field.matchType}=="left"||${field.matchType}=="right")
		String ${field.field} = (String)conditionMap.get("${field.field}");
		if(StringUtils.isNotBlank(${field.field})) {
			conditions.append("and t.${field.columnName} like ? ");
			values.add("%"+${field.field}+"%");
		}
#elseif(${field.matchType}=="dateRange")
		String beginTime_${field.field} = (String)conditionMap.get("beginTime_${field.field}");
		String endTime_${field.field} = (String)conditionMap.get("endTime_${field.field}");
		
		if(StringUtils.isNotBlank(beginTime_${field.field})) {
			conditions.append(" and t.${field.columnName} >= ? ");
			values.add(beginTime_${field.field}+" 00:00:00");
		}
		
		if(StringUtils.isNotBlank(endTime_${field.field})) {
			conditions.append(" and t.${field.columnName} <= ? ");
			values.add(endTime_${field.field}+" 23:59:59");
		}
		    
#elseif(${field.matchType} == "select")
		String ${field.field} = (String)conditionMap.get("${field.field}");
		if(StringUtils.isNotBlank(${field.field})) {
			conditions.append(" and t.${field.columnName} = ? ");
			values.add(${field.field});
		} 
#end
#end

		String orderTypeStr = (String)conditionMap.get("orderTypeStr");
		if(StringUtils.isNotBlank(orderTypeStr)) {
			conditions.append(" order by "+orderTypeStr);
		}else {
			conditions.append(" order by t.create_time desc ");
		}
		
		List<${model.tableName}> list = null;
		int count = 0;
		
		try {
			count = (int)${model.tableName}.count(conditions.toString(), values.toArray());
			list = ${model.tableName}.find(conditions.toString(), values.toArray()).fetch();
		}catch (Exception e) {
			e.printStackTrace();
			Logger.info("查询${model.comment}列表时："+e.getMessage());
			error.code = -1;
			error.msg = "查询${model.comment}列表失败";
			
			return null;
		}
		
		 
		
		PageBean<${model.tableName}> page = new PageBean<${model.tableName}>();

		page.page = list;
		page.totalCount = count;
		page.conditions = conditionMap;
		
		error.code = 0;

		return page;
	}
	
	
	/**
	 * 查询所有${model.comment},分页
	 * @param currPage
	 * @return
	 */
	public static PageBean<Map<String,Object>> query${model.model}Page(Map conditionMap,ErrorInfo error) {
		error.clear();
		 
 		int currPage = Constants.ONE;
 		int pageSize = Constants.PAGE_SIZE;
 		
 		String currPageStr = (String)conditionMap.get("currPage");
 		if(NumberUtil.isNumericInt(currPageStr)) {
 			currPage = Integer.parseInt(currPageStr);
 		}
 		String pageSizeStr = (String)conditionMap.get("pageSize");
 		if(NumberUtil.isNumericInt(pageSizeStr)) {
 			pageSize = Integer.parseInt(pageSizeStr);
 		}
 		
 		
 		StringBuffer sql = new StringBuffer("");
		sql.append(SQLTempletes.PAGE_SELECT);
		sql.append(" t.* ");
#foreach ($field in $fieldList)
#if($field.inputType == "select"&&${field.inputValueTwo} != "")
		sql.append(",t.$field.columnName,dic${velocityCount}.${field.inputValueTwo} as ${field.columnName}_name ");
#end
#end
		sql.append(" from ${model.tableName} t ");
#foreach ($field in $fieldList)
#if($field.inputType == "select"&&${field.inputValueTwo} != "")
		sql.append(" left join ${field.inputValueOne} dic$velocityCount ON t.${field.columnName}=dic$velocityCount.`id` ");
#end
#end
		sql.append(" where t.delete_status =0 ");//或将sql语句移至SQLTempletes
		
		List<Object> paramsCount = new ArrayList<Object>();
		List<Object> params = new ArrayList<Object>();
		String id = (String)conditionMap.get("id");
		if(StringUtils.isNotBlank(id)) {
			sql.append("and t.id = ? ");
			params.add(id);
			paramsCount.add(id);
		}
#foreach( $field in $fieldList )
#if(${field.matchType}=="any"||${field.matchType}=="eq"||${field.matchType}=="left"||${field.matchType}=="right")
		String ${field.field} = (String)conditionMap.get("${field.field}");
		if(StringUtils.isNotBlank(${field.field})) {
			sql.append("and t.${field.columnName} like ? ");
			params.add("%"+${field.field}+"%");
			paramsCount.add("%"+${field.field}+"%");
		}
#elseif(${field.matchType}=="dateRange")
		String beginTime_${field.field} =  (String)conditionMap.get("beginTime_${field.field}");
		String endTime_${field.field} =  (String)conditionMap.get("endTime_${field.field}");
		
		if(StringUtils.isNotBlank(beginTime_${field.field})) {
			sql.append("and t.${field.columnName} >= ? ");
			params.add(beginTime_${field.field}+" 00:00:00");
			paramsCount.add(beginTime_${field.field}+" 00:00:00");
		}
		
		if(StringUtils.isNotBlank(endTime_${field.field})) {
			sql.append("and t.${field.columnName} <= ? ");
			params.add(endTime_${field.field}+" 23:59:59");
			paramsCount.add(endTime_${field.field}+" 23:59:59");
		}
		    
#elseif(${field.matchType} == "select")
		String ${field.field} = (String)conditionMap.get("${field.field}");
		if(StringUtils.isNotBlank(${field.field})) {
			sql.append("and t.${field.columnName} = ? ");
			params.add(${field.field});
			paramsCount.add(${field.field});
		} 
#end
#end

		String orderTypeStr = (String)conditionMap.get("orderTypeStr");
		if(StringUtils.isNotBlank(orderTypeStr)) {
			sql.append("order by "+orderTypeStr);
		}else {
			sql.append("order by t.create_time desc ");
		}
		 

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		int count = 0;
		
		//start
		//Logger.error("分页查询${model.comment}时："+sql.toString());
		//end
		
		try {
			EntityManager em = JPA.em();
            Query query = em.createNativeQuery(sql.toString());
            for(int n = 1; n <= params.size(); n++){
                query.setParameter(n, params.get(n-1));
            }
            query.setFirstResult((currPage - 1) * pageSize);
            query.setMaxResults(pageSize);
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            list = query.getResultList();
            
            count = QueryUtil.getQueryCountByCondition(em, sql.toString(), paramsCount);
            
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error("分页查询${model.comment}："+e.getMessage());
			error.code = -1;
			error.msg = "分页查询${model.comment}列表时出现异常！";
			
			return null;
		}
		
		PageBean<Map<String,Object>> pageBean = new PageBean<Map<String,Object>>();
		pageBean.pageSize = pageSize;
		pageBean.currPage = currPage;
		pageBean.totalCount = count;
		pageBean.conditions = conditionMap;
		
		pageBean.page = list;
		
		error.code = 0;
		
		return pageBean;
	}
	
	
	
	/**
	 * 根据${model.comment}ID查询
	 * 
	 * @param id
	 * @param error
	 * @return
	 */
	public static ${model.tableName} query${model.model}ById(long id,ErrorInfo error) {
	
		${model.tableName} ${model.modelL}Entity = null;
		error.clear();

		try {
			${model.modelL}Entity = ${model.tableName}.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.info("${model.comment}查询，根据${model.comment}ID查询${model.comment}时：" + e.getMessage());
			error.code = -1;
			error.msg = "查询${model.comment}失败";
		}

		error.code = 0;

		return ${model.modelL}Entity;
	}
	
#foreach($field in $fieldList)
#if($field.findBy&&$field.field!="id")
	/**
	 * 根据${field.comment}条件查询实体
	 * @param error
	 * @return
	 */
	public static ${model.tableName} select${model.model}By${field.fieldUp}(String ${field.field}, ErrorInfo error) {
		error.clear();
		
		String sql = "select new ${model.tableName}(#foreach ($field in $fieldList)s.$field.columnName#if($velocityCount != $fieldList.size()),#end#end) "
				+ " from ${model.tableName} where ${field.columnName} = ?  and delete_status=0 order by create_time desc";
		
		${model.tableName} entity = new ${model.tableName}();
		
		try {
			entity = (${model.tableName})${model.tableName}.find(sql, ${field.field}).first();
		}catch(Exception e) {
			e.printStackTrace();
			Logger.info("根据${field.comment}条件查询实体时："+e.getMessage());
			
			return null;
		}
		
		error.code = 0;
		
		return entity;
	}
#end
#if($field.findAllBy)
	/**
	 * 根据${field.comment}条件查询所有实体
	 * @param error
	 * @return
	 */
	public static List<${model.tableName}> findAllBy${model.model}By${field.fieldUp}(String ${field.field}, ErrorInfo error) {
		error.clear();
		
		String sql = "select new ${model.tableName}(#foreach ($field in $fieldList)s.$field.columnName#if($velocityCount != $fieldList.size()),#end#end) "
				+ " from ${model.tableName} where ${field.columnName} = ? and delete_status=0 order by create_time desc";
		
		List<${model.tableName}> entitys =  new ArrayList<${model.tableName}>();
		
		try {
			entitys = ${model.tableName}.find(sql, ${field.field}).fetch();
		}catch(Exception e) {
			e.printStackTrace();
			Logger.info("根据${field.comment}条件查询所有实体时："+e.getMessage());
			
			return null;
		}
		
		error.code = 0;
		
		return entitys;
	}
#end
#end	
	
	
	/**
	 * 添加${model.comment}
	 */
	public int add${model.model}(int flag,${model.tableName} entity,ErrorInfo error){
		 
		entity.create_time = new Date();
		entity.delete_status = false;
#foreach ($field in $fieldList)
#if(${field.inputType}=="htmleditor")
		entity.${field.columnName} = Templets.replaceAllHTML(entity.${field.columnName});// ${field.comment}
#end
#end
		try {
			entity.save();
		} catch (Exception e) {
			e.printStackTrace();
			error.msg = "保存${model.comment}失败";
			error.code = -1;
			return -2;
		} 
		if(flag==0)
			DealDetail.supervisorEvent(Supervisor.currSupervisor().id, SupervisorEvent.XXXX,"添加${model.comment}", error);
		else
			DealDetail.userEvent(User.currUser().id, SupervisorEvent.XXXX,"添加${model.comment}", error);

		if (error.code < 0) {
			JPA.setRollbackOnly();

			return error.code;
		}
		
		error.code = 0;
		error.msg = "${model.comment}添加成功";
		this._id = entity.id;
		
		return 0;
	}
	
	
	/**
	 * 编辑${model.comment} 
	 * @param id
	 * @param error
	 * @return
	 */
	public int edit(int flag,long id, ErrorInfo error) {
		error.clear();

		${model.tableName} ${model.modelL}Entity = null;

		try {
			${model.modelL}Entity = ${model.tableName}.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.info("编辑${model.comment}查询，根据${model.comment}ID查询${model.comment}信息时：" + e.getMessage());
			error.code = -1;
			error.msg = "查询${model.comment}失败";

			return error.code;
		}

#foreach ($field in $fieldList)
#if(${field.field}!="id"&&${field.field}!="createUser"&&${field.field}!="createTime"&&${field.field}!="deleteStatus")
#if(${field.inputType}=="htmleditor")
		${model.modelL}Entity.${field.columnName} = Templets.replaceAllHTML(this.${field.field});// ${field.comment}
#else
		${model.modelL}Entity.${field.columnName} = this.${field.field};// ${field.comment}
#end
#end
#end 
		try {
			${model.modelL}Entity.save();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.info("编辑${model.comment}，保存编辑的${model.comment}时：" + e.getMessage());
			error.msg = "保存${model.comment}失败";
			error.code = -1;
			return -1;
		}
		if(flag==0)
			DealDetail.supervisorEvent(Supervisor.currSupervisor().id, SupervisorEvent.XXXX,"编辑${model.comment}", error);
		else
			DealDetail.userEvent(User.currUser().id, SupervisorEvent.XXXX,"编辑${model.comment}", error);

		if (error.code < 0) {
			JPA.setRollbackOnly();

			return error.code;
		}

		error.code = 0;
		error.msg = "编辑${model.comment}成功";

		return 0;
	}
	
	/**
	 * 删除${model.comment} 
	 * @param id
	 * @param error
	 * @return
	 */
	public static int delete(int flag,long id, ErrorInfo error) {
		 
		
		//String sql = "delete from ${model.tableName} where id = ?";
		String sql = "update ${model.tableName} set delete_status=1 where id = ?";
		int rows = 0;
		
		try {
			rows = JpaHelper.execute(sql, id).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.info("删除${model.comment}时：" + e.getMessage());
			error.code = -1;
			error.msg = "删除${model.comment}失败";
			
			return error.code;
		}
		
		if(rows == 0) {
			JPA.setRollbackOnly();
			error.code = -1;
			error.msg = "数据未更新";
			
			return error.code;
		}
		if(flag==0)
			DealDetail.supervisorEvent(Supervisor.currSupervisor().id, SupervisorEvent.XXXX,"删除${model.comment}", error);
		else
			DealDetail.userEvent(User.currUser().id, SupervisorEvent.XXXX,"删除${model.comment}", error);

		if (error.code < 0) {
			JPA.setRollbackOnly();

			return error.code;
		}
		
		error.code = 0;
		error.msg = "删除${model.comment}成功";
		
		return error.code;
	}
	
	
	/**
	 * 批量${model.comment} 删除
	 * @param supervisorId
	 * @param error
	 */
	public static void delete(int flag,String[] ids, ErrorInfo error) {
		error.clear();
		
		if(ids == null || ids.length == 0) {
			error.code = -1;
			error.msg = "请选择要删除的记录";
			
			return;
		}
		
		StringBuffer typeString = new StringBuffer("(");
		
		for(int i=0;i<ids.length;i++) {
			typeString.append("?,");
		}
		
		typeString.replace(typeString.length()-1, typeString.length(), ")");
		
//		String sql = "delete from ${model.tableName} where id in "+typeString.toString(); 
		String sql = "update ${model.tableName} set delete_status=1 where id in "+typeString.toString(); 
		
		Query query = JPA.em().createQuery(sql); 
		
		for(int i=0;i<ids.length;i++) {
			query.setParameter(i+1, ids[i]); 
		}
		
		int rows1 = 0;
		
		try{
			rows1 = query.executeUpdate(); 
		}catch(Exception e) {
			JPA.setRollbackOnly();
			e.printStackTrace();
			Logger.info("删除${model.comment}时："+e.getMessage());
			error.code = -1;
			error.msg = "删除时${model.comment}出现异常";
			
			return;
		}
		if(flag==0)
			DealDetail.supervisorEvent(Supervisor.currSupervisor().id, SupervisorEvent.XXXX, "批量删除${model.comment} ", error);
		else
			DealDetail.userEvent(User.currUser().id, SupervisorEvent.XXXX,"批量删除${model.comment} ", error);
		if (error.code < 0) {
			JPA.setRollbackOnly();

			return ;
		}
		
		error.code = 0;
		error.msg = "删除成功";
	}
}
